
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>表单处理</title>
    <style>
        body {
            background: #663399;
        }
        legend {
            color: white;
            font-size: 24px;
            font-weight: bold;
            text-align: left;
        }
        fieldset {
            padding: 20px;
            text-align: center;
        }
        input {
            margin: 20px;
        }
        label {
            width: 50px;
            text-align: left;
            display: inline-block;
        }
    </style>
</head>
<body>
    <form action="/" method="POST" onsubmit="return controller()">
        <fieldset>
            <legend>用户登录</legend><br />
            <label for="username">用户名</label>
            <input type="username" name="username" id="username" autocomplete="on" /><br />
            <label for="password">密码</label>
            <input type="password" name="password" id="password" /><br />
            <input type="submit" value="提交">
            <input type="reset" value="重置">
        </fieldset>
    </form>
</body>
<script>
    const form = document.querySelector('form');
    function requiredVerify(arr) {
        return arr.filter(item => item.value.length === 0);
    }
    function efficientVerify(arr) {
        return arr.filter(item => item.value.length < 8 || item.value.length > 20);
    }
    function controller() {
        const efficient = efficientVerify([form.username, form.password]),
            required = requiredVerify([form.username, form.password]);
        if (required.length) {
            const str = document.querySelector(`label[for=${required[0].id}]`).innerText;
            alert(str + '不能为空');
            required[0].focus();
            return false;
        }
        else if (efficient.length) {
            const str = document.querySelector(`label[for=${efficient[0].id}]`).innerText;
            alert(str + '必须在8-20位')
            efficient[0].focus();
            return false;
        }
        return true;
    }

</script>